<template>
  <div class="vxe-table-container">
    <div class="vxe-table-container__header">
      <!-- <FilterVisible v-if="columnList.length" :column="columnList" :table="tableRef" v-bind="$attrs" @column-sort="columnSort" /> -->
      <div v-if="checkedLength > 0" class="operate-control">
        <div>
          <label>
            <span>已选</span>
            <span class="color-primary">{{ checkedLength }}</span>
            <span>项</span>
          </label>
          <div class="operate-control-button">
            <slot name="operate" />
          </div>
        </div>
        <div class="cp" @click="clear">取消全选</div>
      </div>
      <vxe-table
        ref="tableRef"
        :data="data"
        :height="height"
        :scroll-y="{ enabled: true, gt: 0 }"
        :loading="loading"
        :cell-class-name="cellClassName"
        show-overflow
        @scroll="scrollEvent"
        @filter-change="filterChangeEvent"
      >
        <template v-for="item in columnList" :key="item.field">
          <!-- 自定义checkbox -->
          <vxe-column v-if="item.type === 'seq'" :fixed="item.fixed" width="42" :edit-render="{}" class-name="cell-checkbox">
            <template #header="{ row }">
              <div class="text-center">
                <a-checkbox v-model:checked="isCheckedAll" @click="onChangeCheckboxAll" />
              </div>
            </template>
            <template #default="{ row, rowIndex }">
              <div :class="{ 'checkbox-checked': row.checked }">
                <span class="cell-checkbox-index">{{ rowIndex + 1 }}</span>
                <span class="cell-checkbox-wrap"><a-checkbox v-model:checked="row.checked" :id="row[id]" @click="onChangeCheckbox" /></span>
              </div>
            </template>
          </vxe-column>
          <!-- 操作栏 -->
          <vxe-column v-else-if="item.type === 'operate'" :title="item.title || '操作'" :width="item.width" :fixed="item.fixed" :align="item.align" :class-name="item.className">
            <template #default="{ row }"><slot name="operate" :row="row" /></template>
          </vxe-column>
          <!-- 插槽内容 -->
          <vxe-column
            v-else-if="item.type === 'slot'"
            :field="item.field"
            :title="item.title"
            :width="item.width"
            :fixed="item.fixed"
            :align="item.align"
            :class-name="item.className"
            :visible="item.visible"
          >
            <template #default="{ row }"><slot :name="item.slotName" :row="row" /></template>
          </vxe-column>
          <vxe-column v-else :field="item.field" :title="item.title" :width="item.width" :fixed="item.fixed" :align="item.align" :visible="item.visible">
            <template #default="{ row, column }">
              <!-- 金额 -->
              <template v-if="item.type === 'price'">
                <span>{{ thousandth({ value: row[item.field], theme: item.theme, column }) }}</span>
              </template>
              <!-- 默认渲染 -->
              <template v-else>
                <span>{{ formats(row?.[item.field]) }}</span>
              </template>
            </template>
          </vxe-column>
        </template>
      </vxe-table>
    </div>
    <div class="vxe-table-container__footer">
      <div class="page-count">第0条,共计{{ total }}条</div>
      <div class="pagination-wrap">
        <div class="pagination-wrap__select">
          <span>每页</span>
          <a-select v-model:value="pageSize" style="width: 70px" @change="changePageSize">
            <a-option v-for="page in pageSizeOptions" :key="page" :value="page">{{ page }}</a-option>
          </a-select>
          <span>条</span>
        </div>
        <a-pagination
          v-model:current="current"
          v-model:page-size="pageSize"
          show-quick-jumper
          :total="total"
          :page-size-options="pageSizeOptions"
          :disabled="loading"
          show-size-changer
          @change="onChange"
        />
      </div>
    </div>
  </div>
</template>
<script lang="ts" setup>
  import { ref, Ref, onMounted, nextTick, getCurrentInstance } from "vue"
  import { IS_NULL_CONTENT } from "@/constant/index"
  import tableEmits from "./emits"
  import { PAGE, PAGE_SIZE, PAGE_SIZE_OPTIONS } from "@/constant/index"
  import { VxeTableInstance } from "vxe-table"
  import { thousandth } from "@/utils"
  import FilterVisible from "./filterVisible/index.vue"
  import type { columnInterface, filterInterface } from "./interface"

  interface ExposedProps {
    setLoading: () => void
    setHeight: () => void
    setTotal: () => number
    tableRef: any
    // 其他暴露的属性
  }
  // proxy
  const { proxy } = getCurrentInstance()!
  const loading = ref(false)
  const emits = defineEmits(tableEmits)
  const props = defineProps({
    id: {
      type: String,
      default: "id",
    },
    data: {
      type: Array,
      default: () => [],
    },
    columns: {
      type: Array<columnInterface>,
      default: () => [],
    },
    cellClassName: Object as () => any,
    autoHeight: Boolean,
  })
  // 表格对象
  const tableRef = ref<VxeTableInstance<any>>()
  // 列 排序
  const columnList: columnInterface = ref([])
  // 是否显示操作控件
  const checkedLength = ref<number>(0)
  // 格式化单元格
  const formats = (cellValue: any) => {
    const isEmpty = ["", null, undefined]
    return isEmpty.includes(cellValue) ? IS_NULL_CONTENT : cellValue
  }
  // 是否全选
  const isCheckedAll = ref(false)
  /**
   * page
   */
  const pageSizeOptions = ref<string[]>(PAGE_SIZE_OPTIONS)
  const current = ref(PAGE)
  const pageSize = ref(PAGE_SIZE)
  const total = ref(0)
  const height = ref(0)
  // loading
  const setLoading = (value: boolean) => (loading.value = value)

  const scrollEvent = (params: any) => {
    // console.log(
    //   `纵向：${params.isY} 横向：${params.isX} 滚动距离：X：${params.scrollLeft}Y：${params.scrollTop} 滚动条宽高：${params.scrollWidth}*${params.scrollHeight} 滚动容器宽高：${params.bodyWidth}*${params.bodyHeight}`
    // )
    // if (params.scrollTop <= 0) {
    //   console.log("已经到顶部了")
    // } else if (params.scrollTop + params.bodyHeight >= params.scrollHeight) {
    //   console.log("已经到底部了")
    // }
  }

  const filterChangeEvent = ({ column, field, values, datas, filterList, $event }: filterInterface) => {
    emits("filter-change", { column, field, values, datas, filterList, $event })
  }

  /**
   * 设置高度
   */
  const setHeight = () => {
    nextTick(() => {
      const inner = document.querySelector(".vxe-table-container__header")
      height.value = props.autoHeight ? 0 : (inner as HTMLElement)?.offsetHeight
    })
  }
  /**
   * 设置页面
   */
  const setTotal = (value: number) => (total.value = value)
  /**
   * 分页
   */
  const changePageSize = (val: number) => {
    emits("update:size", val)
    emits("page", current.value, val)
  }
  const onChange = (page: number, pageSize: number) => {
    emits("update:page", page)
    emits("update:size", pageSize)
    emits("page", page, pageSize)
  }
  /**
   * 取消全选
   */
  const clear = () => {
    onChangeCheckboxAll({
      target: {
        checked: false,
      },
    })
  }
  /**
   * 全选复选框
   */
  const onChangeCheckboxAll = (e: any) => {
    const checked = e.target.checked
    // 操作控件
    checkedLength.value = checked ? props.data.length : 0
    props.data.forEach((item: any) => (item.checked = checked))
    // 全选状态
    isCheckedAll.value = checked
    emits("checkbox-all", checked ? props.data : [])
  }
  /**
   *
   * 单选复选框
   */
  const onChangeCheckbox = async (e: any) => {
    // 选择状态
    const checked = e.target.checked
    // 过滤当前数据
    const rowData: any = props.data.filter((row: any) => row[props.id] === e.target[props.id])[0]
    // 更新当前数据选择状态
    rowData.checked = checked
    // 获取选择的数据
    checkedLength.value = props.data.filter((item: any) => item.checked).length || 0
    // 更新“全部选中”复选框
    isCheckedAll.value = checkedLength.value === props.data.length
    // 操作控件
    // 回调
    emits("checkbox-change", rowData, rowData.checked, e)
  }
  /**
   * 获取选择中的数据
   */
  const getChecked = () => props.data.forEach((item: any) => item.checked)
  /**
   * 列数据筛选排序、隐藏、显示
   */
  const columnSort = async (columns: []) => {
    columnList.value = []
    await nextTick()
    columnList.value = columns
    const $table = tableRef.value
    $table && $table.refreshColumn()
  }
  /**
   * 生命周期
   */
  onMounted(async () => {
    await nextTick()
    window.onresize = () => setHeight()
    setHeight()
  })
  /**
   * watch
   */
  watch(
    () => props.columns,
    (val) => {
      columnList.value = val
    },
    {
      immediate: true,
    }
  )

  defineExpose({
    setLoading,
    setHeight,
    setTotal,
    getChecked,
  })
</script>
<style lang="scss" scoped>
  .vxe-table-container {
    display: flex;
    flex-direction: column;
    height: calc(100% - 1px);
    box-sizing: border-box;
  }
  .vxe-table-container__header {
    position: relative;
    flex: 1;
    height: 0;
  }
  .vxe-table-container__footer {
    padding-top: 12px;
    display: flex;
    align-items: center;
    justify-content: space-between;
  }
  .cell-checkbox {
    cursor: pointer;
    .cell-checkbox-wrap {
      text-align: center;
      display: none;
    }
    &:hover,
    .checkbox-checked {
      .cell-checkbox-index {
        display: none;
      }
      .cell-checkbox-wrap {
        display: block;
      }
    }
  }
  .pagination-wrap {
    display: flex;
  }
  .pagination-wrap__select {
    margin-right: 4px;
    span {
      margin: 0 4px;
    }
  }
  .operate-control {
    padding: 0 16px;
    display: flex;
    align-items: center;
    justify-content: space-between;
    position: absolute;
    top: 1px;
    right: 1px;
    left: 42px;
    height: var(--vxe-ui-table-header-height-default);
    background-color: var(--n-black-bg);
    z-index: 4;
    > div {
      display: flex;
      align-items: center;
      cursor: pointer;
    }
    label {
      color: var(--n-black-light-1);
    }
  }
  .operate-control-button {
    display: flex;
    > .contron-item {
    }
    i {
      width: 16px;
      height: 16px;
    }
  }
  :slotted(.contron-item) {
    padding: 0 8px;
    display: flex;
    align-items: center;
    height: 32px;
    border-radius: var(--n-radius);
    color: var(--n-black-light-2);
    cursor: pointer;
    transition: var(--n-transition);
    margin-left: 8px;
    &:hover:not(.is-disabled) {
      background-color: var(--n-black-border);
    }
  }
  :slotted(.is-disabled) {
    opacity: 0.5;
    cursor: no-drop;
  }
</style>
